/*******************************************************************************
 * Copyright 2020 huanggefan.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 ******************************************************************************/

package service

import (
	"context"
	"database/sql"
	"strings"

	"gitee.com/WisdomClassroom/core"
	"gitee.com/WisdomClassroom/core/models"
	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/question/glb"
	"google.golang.org/grpc/metadata"
	"gorm.io/gorm"
)

func (s *Service) UpdateQuestion(ctx context.Context, request *pb.UpdateQuestionRequest) (*pb.UpdateQuestionResponse, error) {
	md, ok := metadata.FromIncomingContext(ctx)
	if !ok {
		glb.Logger.Error("no metadata")
	}
	token, err := core.UnpackTokenFromMetadata(md)
	if err != nil {
		return &pb.UpdateQuestionResponse{Status: &pb.ResponseStatus{
			Code: core.ResponseStatusCodeNotAuth, Message: err.Error(),
		}}, nil
	}

	question := &models.Question{UUID: request.GetUUID()}

	err = glb.DB.Take(question).Error
	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return &pb.UpdateQuestionResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeOtherError,
				Message: "题目不存在",
			}}, nil
		}
		glb.Logger.Error(err.Error())
		return updateQuestionRespSvrErr, nil
	}

	if !token.IsManager {
		managerUUID := ""
		err = glb.DB.Raw(
			`select course_manager_bind.manager_uuid from course_manager_bind
				where course_manager_bind.course_uuid = (
					select course_model.uuid from chapter_model
					join course_model on course_model.uuid = chapter_model.course_uuid
					where chapter_model.uuid = ?
				) and course_manager_bind.manager_id = ? `, question.ChapterUUID, token.AccountID,
		).Scan(&managerUUID).Error
		if err != nil {
			glb.Logger.Error(err.Error())
			return updateQuestionRespSvrErr, nil
		}
		if managerUUID == "" {
			return &pb.UpdateQuestionResponse{Status: &pb.ResponseStatus{
				Code:    core.ResponseStatusCodeNotAuth,
				Message: "用户没有权限",
			}}, nil
		}
	}

	question.Question = sql.NullString{String: request.GetQuestion(), Valid: true}
	question.Analysis = sql.NullString{String: strings.ToValidUTF8(request.GetAnalysis(), ""), Valid: true}
	question.AnswerA = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerA(), ""), Valid: true}
	question.AnswerB = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerB(), ""), Valid: true}
	question.AnswerC = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerC(), ""), Valid: true}
	question.AnswerD = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerD(), ""), Valid: true}
	question.AnswerE = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerE(), ""), Valid: true}
	question.AnswerF = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerF(), ""), Valid: true}
	question.AnswerG = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerG(), ""), Valid: true}
	question.AnswerH = sql.NullString{String: strings.ToValidUTF8(request.GetAnswerH(), ""), Valid: true}
	question.IsA = sql.NullBool{Bool: request.GetIsA(), Valid: true}
	question.IsB = sql.NullBool{Bool: request.GetIsB(), Valid: true}
	question.IsC = sql.NullBool{Bool: request.GetIsC(), Valid: true}
	question.IsD = sql.NullBool{Bool: request.GetIsD(), Valid: true}
	question.IsE = sql.NullBool{Bool: request.GetIsE(), Valid: true}
	question.IsF = sql.NullBool{Bool: request.GetIsF(), Valid: true}
	question.IsG = sql.NullBool{Bool: request.GetIsG(), Valid: true}
	question.IsH = sql.NullBool{Bool: request.GetIsH(), Valid: true}
	question.IsTrue = sql.NullBool{Bool: request.GetIsTrue(), Valid: true}
	question.Level = sql.NullInt32{Int32: request.GetLevel(), Valid: true}
	question.IsExamQuestion = sql.NullBool{Bool: request.GetIsExamQuestion(), Valid: true}

	err = glb.DB.Transaction(func(tx *gorm.DB) error {
		err = tx.Model(question).Updates(question).Error
		if err != nil {
			return err
		}
		return nil
	})
	if err != nil {
		glb.Logger.Error(err.Error())
		return updateQuestionRespSvrErr, nil
	}

	return &pb.UpdateQuestionResponse{
		Status: &pb.ResponseStatus{Code: core.ResponseStatusCodeSuccess},
	}, nil
}
